// Copyright (c) 2021, yuxinyong and contributors
// For license information, please see license.txt

frappe.ui.form.on('Plan Order', {
	refresh: function(frm) {
		if (!frm.doc.converted && frm.doc.convertible) {
			if (frm.doc.supply_method=='Manufacture'){
				frm.add_custom_button(__("Convert to Work Order"), ()=> {
					frappe.call({
						method: "zelin_am.agile_manufacturing.doctype.plan_order.plan_order.create_work_order",
						args:{
							plan_order: frm.doc
						},
						freeze: true,
						freeze_message: __("Creating Work Order..."),
					}).then((r)=>{
						var doclist = frappe.model.sync(r.message);
						frm.set_value('converted', 1)
						frm.save()
						frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
					});
				}).addClass('btn-primary');
			}
			else if (in_list(['Purchase', 'Subcontract'], frm.doc.supply_method) &&	frm.doc.supplier) {
				frm.add_custom_button(__("Convert to Purchase Order"), ()=> {
					frappe.call({
						method: "zelin_am.agile_manufacturing.doctype.plan_order.plan_order.create_purchase_order",
						args:{
							plan_order: frm.doc
						},
						freeze: true,
						freeze_message: __("Creating Purchase Order..."),
					}).then((r)=>{
						var doclist = frappe.model.sync(r.message);
						frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
					});
				}).addClass('btn-primary');
			}
			else if (in_list(['Customer Provided'], frm.doc.supply_method) &&	frm.doc.customer) {
				frm.add_custom_button(__("Convert to Material Request"), ()=> {
					frappe.call({
						method: "zelin_am.agile_manufacturing.doctype.plan_order.plan_order.create_material_request",
						args:{
							plan_order: frm.doc
						},
						freeze: true,
						freeze_message: __("Creating Material Request..."),
					}).then((r)=>{
						var doclist = frappe.model.sync(r.message);
						frappe.set_route("Form", doclist[0].doctype, doclist[0].name);
					});
				}).addClass('btn-primary');
			}
		}
	}
});
